import { t } from 'i18next'
import { useState, useEffect } from 'react'
import { SelectItem, Vmp } from '../interface'
import { Alert } from '@/components/Alert'
import { useRequest } from 'ahooks'
import { useMccStore } from '../../../store'
import { fetchGetVmpPlanList, fetchGetVmpPlan, fetchStartVmp, fetchChangeVmp } from '@/api/manager/vmp'
import { vmpStyleData } from '../VmpView/interface'
import { fetchStartMTVmp, fetchChangeMTVmp } from '@/api/manager/mtVmp'
import { useVmpTypeStore } from '../store.get'
import { useManagerStore } from '../../main/manager/store'
import { transVmpDTO } from '../translator'
import { ChairmanVmpData } from '@/api/manager/mtVmp/interface'

export default function useService({ getVmpParam }: { getVmpParam: () => Vmp | null }) {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const useStore = useVmpTypeStore((state) => state.getStore())
	const { update, localStoragePreName, vmpParamsName, vmpState, isShowPlanOperateModal } = useStore((state) => ({
		update: state.update,
		localStoragePreName: state.localStoragePreName,
		vmpParamsName: state.vmpParamsName,
		vmpState: state.vmpState,
		isShowPlanOperateModal: state.isShowPlanOperateModal,
	}))
	const isVmp = useVmpTypeStore((state) => state.type === 'vmp')
	const [planValue, setPlanValue] = useState('0') //预案id
	const [planOptions, setPlanOptions] = useState<SelectItem[]>([]) //预案选项
	const [planTempValue, setPlanTempValue] = useState('0') //临时预案id
	const [valueSource] = useState(vmpStyleData) /**下拉数据源 */
	const [beSelectPlanOptionsItem, setBeSelectPlanOptionsItem] = useState<SelectItem>() //预案选项
	const { data: vmpPlanData, run } = useRequest(() => fetchGetVmpPlanList(meetingMoid), { manual: true })
	useEffect(() => {
		if (isShowPlanOperateModal) {
			run()
		}
	}, [isShowPlanOperateModal])
	useEffect(() => {
		if (vmpPlanData && vmpPlanData.success) {
			let arr: SelectItem[] = vmpPlanData.data
				? vmpPlanData.data.map((item) => {
						let _valueSourceItem = valueSource.find((_item, index) => {
							return _item.id === item.layout
						})
						return {
							label: item.name,
							value: item.id,
							layout: _valueSourceItem?.id,
							className: _valueSourceItem?.className || '',
							count: '',
						}
				  })
				: []
			setPlanOptions(arr)
		}
	}, [vmpPlanData])
	useEffect(() => {
		if (vmpState === 1) {
			let _item = planOptions.find((item) => item.label === vmpParamsName)
			_item && setBeSelectPlanOptionsItem(_item)
			setPlanValue(_item?.value ?? '0')
			setPlanTempValue(_item?.value ?? '0') /**临时预案赋值当前预案值*/
		}
		if (vmpState === 0) {
			let _item = planOptions.find((item) => item.label === localStoragePreName)
			_item && setBeSelectPlanOptionsItem(_item)
			setPlanValue(_item?.value ?? '0')
			setPlanTempValue(_item?.value ?? '0') /**临时预案赋值当前预案值*/
		}
	}, [vmpState, vmpParamsName, planOptions])
	// 关闭选择预案模态框
	const handleCloseSelectPlanModal = () => {
		update({ isShowPlanOperateModal: false }) /**关闭选中预案模态框 */
		setPlanTempValue('0') /**临时预案清空*/
	}
	// 选则预案勾选
	const handleCheckPlan = (plan_value: string) => {
		setPlanTempValue(plan_value) /**临时预案赋值当前预案值*/
	}
	/**选中预案*/
	const selectPlan = () => {
		let _planTempValue = planTempValue
		changePlan(_planTempValue) /**切换预案 */
		setPlanValue(_planTempValue) /**将临时预案赋值给选中预案 */
		handleCloseSelectPlanModal()
	}
	//载入预案
	const changePlan = (id: string) => {
		fetchGetVmpPlan(meetingMoid, id).then(async (res) => {
			if (res.success) {
				setPlanValue(id)
				let data = transVmpDTO(res)
				if (isVmp) {
					if (vmpState === 0) {
						const res = await fetchStartVmp(meetingMoid, data)
						if (res.success) {
							update({ _isEdit: false, _message_flag: 'vmp_stop' })
						} else {
							Alert(res.description || t('操作失败'))
						}
					} else {
						const res = await fetchChangeVmp(meetingMoid, data)
						if (res.success) {
							update({ _isEdit: false, _message_flag: 'vmp_apply' })
						} else {
							Alert(res.description || t('操作失败'))
						}
					}
				} else {
					/**此处是外部终端画面合成预案载入切换预案或者开始终端画面合成*/
					let _data = { ...data, broadcast: 0 }
					if (vmpState === 0) {
						const chairman = useManagerStore.getState().chairman
						if (!chairman?.mtKey) return
						const res = await fetchStartMTVmp(meetingMoid, {
							...data,
							vmp_mt: {
								mt_id: chairman.mtid,
							},
						} as unknown as ChairmanVmpData)
						if (res.success) {
							update({ _isEdit: false, _message_flag: 'mtVmp_manager_stop' })
						} else {
							Alert(res.description || t('操作失败'))
						}
					} else {
						const chairman = useManagerStore.getState().chairman
						if (!chairman?.mtKey) return
						const res = await fetchChangeMTVmp(meetingMoid, chairman.mtid, {
							..._data,
							vmp_mt: { mt_id: chairman.mtid ?? '' },
						} as unknown as ChairmanVmpData)
						if (res.success) {
							update({ _isEdit: false, _message_flag: 'mtVmp_manager_apply' })
						} else {
							Alert(res.description || t('操作失败'))
						}
					}
				}
			}
		})
	}
	return {
		/** 预案选项 */
		planOptions,
		/** 预案选项值 */
		planValue,
		/** 载入预案 */
		changePlan,
		// 关闭预案选择模态框
		handleCloseSelectPlanModal,
		// 勾选预案
		handleCheckPlan,
		planTempValue,
		/**确定选中预案 */
		selectPlan,
		/**被选中预案 */
		beSelectPlanOptionsItem,
	}
}
